using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using log4net;
using log4net.Repository.Hierarchy;

namespace Sedna.Core.Controller.Configurations
{
    public abstract class BaseDataTranslator: IDataTranslator
    {
        protected IDataTranslator next;
        protected bool stopOnFailure = false;

        public IDataTranslator Next
        {
            set { next = value; }
        }

        public bool StopOnFailure
        {
            set { stopOnFailure = value; }
        }

        protected virtual object GetDefaultValue(Control control, object value, Type targetType)
        {
            return null;
        }
        
        public virtual object Translate(Control control, object value)
        {
            return Translate(control, value, null);
        }

        public virtual object Translate(Control control, object value, Type targetType)
        {
            object translatedValue;
            try
            {
                translatedValue = UnsafeTranslate(control, value, null);  
            }
            catch
            {
                translatedValue = GetDefaultValue(control, value, targetType);
                if (stopOnFailure)
                {
                    return translatedValue;                
                }
            }
            if (next!=null)
            {
                return next.Translate(control, translatedValue);
            }
            return translatedValue;
        }

        public abstract object UnsafeTranslate(Control control, object value, Type targetType);
    }
}
